/**
 * @author Stephan Pfaff (http://www.derdaumen.net)
 */

/**
 * ItemContainer Klasse
 * @param type 		String - Typ des ItemContainers (preface, category, project oder button)
 * @param prefix 	String - Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind 
 * @param urlLoad 	String - URL des php Script welches die Inhalte des Containers liefert
 */
function ItemContainer(type, prefix, urlLoad) {
	try {
		this.type = type;
		this.prefix = prefix;
		this.urlLoad = urlLoad;
		this.items = null;
		if(this.type == 'preface')
			this.div_class = 'preface';
		else if(this.type == 'category')
			this.div_class = 'nav nav_horizontal';
		else if(this.type == 'project')
			this.div_class = 'nav nav_vertical';
		else if(this.type == 'button')
			this.div_class = 'content';

		var itemID = type+'Container';
		this.$div = $('#'+itemID);
		this.$scrollWrapper = $('#'+type+'ScrollBox');
		this.scrollThreshold = 100;
		if (!this.$scrollWrapper.length && noPHPMode) {
			var html = ['<div id="'+itemID+'" class="'+this.div_class+'" style="display: none;">'
			            +'<div id="'+type+'ScrollBox" class="scrollBox"></div>'];
			if(this.type == 'project') {
				/*html.push('<div id="" class="navTransparencyTop">');
				var i = 9;	
				for (i=9; i>0; i--) {
					html.push('<div id="" class="percent'+i*10+'" style="top:'+(9-i)*2, 'px; height: 2px; width: 75px; background-image: url(css/frontend/screen/images/menu-transparency-'+i*10+'.png"></div>');
				}
				html.push('</div>');
				html.push('<div id="" class="navTransparencyBottom">');
				var j = 1;
				for (j=1; j<10; j++) {
					html.push('<div id="" class="percent', j*10, '" style="bottom:', (9-j)*2, 'px; height: 2px; width: 75px; background-image: url(css/frontend/screen/images/menu-transparency-', j*10, '.png"></div>');
				}
				html.push('</div>');*/
			}
			html.push('</div>');
			$('#main').append(html.join(''));
			this.$div = $('#'+itemID);
			this.$scrollWrapper = $('#'+type+'ScrollBox');
		}
		
		if (this.type == 'project' || this.type == 'category') {
			var handle = this;
			this.$div.mousemove(function(e){
				handle.scroll(e);
			});
		}
	} catch(e) {
		if(debug) alert('Initialization of Preface failed, missing or wrong parameter! ('+e+')');
	}
};
/**
 * Typ des ItemContainers (preface, category, project oder button)
 */
ItemContainer.prototype.type = null;
/**
 * Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind
 */
ItemContainer.prototype.prefix = null;
/**
 * URL des php Script welches die Inhalte des Containers liefert
 */
ItemContainer.prototype.urlLoad = null;
/**
 * Objekt das die Inhalte des ItemContainers enthält
 */
ItemContainer.prototype.items = null;
/**
 * Das JQuery Objekt des DIVs welches den ItemContainer repräsentiert
 */
ItemContainer.prototype.$div = null;
/**
 * Der Klassename des Container DIVs
 */
ItemContainer.prototype.div_class = null;
/**
 * Der Wrapper für die Scrollfunktion
 */
ItemContainer.prototype.$scrollWrapper = null;
/**
 * Die tatsächliche Höhe des Menüs
 */
ItemContainer.prototype.height = 0;
/**
 * Die tatsächliche Breite des Menüs
 */
ItemContainer.prototype.width = 0;
/**
 * Die Höhe des sichtbaren Menubereichs
 */
ItemContainer.prototype.visibleAreaY = 0;
/**
 * Die Breite des sichtbaren Menubereichs
 */
ItemContainer.prototype.visibleAreaX = 0;
/**
 * Threshold für den Scrollbereich
 */
ItemContainer.prototype.scrollThreshold = 0;
/**
 * Berechnet die Anzahl an Inhalt Elementen im Container
 * @return int - Anzahl der Inhalt Elemente
 */
ItemContainer.prototype.length = function(){
	if (this.items != null) {
		var i = 0;
		for (key in this.items) {
			i++;
		}
		return i;
	} else {
		return -1;
	}
};
/**
 * Löscht alle HTML Elemente im Container-DIV
 * @return void
 */
ItemContainer.prototype.clear = function() {
	this.$scrollWrapper.empty();
};
/**
 * Erstellt Item Objekte aus den geladenen Daten (Category, Project oder Button) und zeigt das Content Grid an
 * @param items_temp 	Object - die geladenen MySQL Datensätze
 * @param params 		Object - Parameter Objekt: {prefix, ctg_id und prj_id} 
 * @param autoSelect	Boolean - Gibt an ob automatisch ein Inhalt-Element ausgewählt werden soll
 * @return
 */
ItemContainer.prototype.createItems = function(items_temp, params, autoSelect) {
	if(noPHPMode) {
		this.clear();
		if(this.type == 'button' || this.type == 'preface')
			var btn_coords = new Array();
	}
	var interactive = new Boolean(true);
	var i = 0;
	for(key in items_temp) {
		var item = items_temp[key];
		//Die geladenen Objekte erstellen und in items speichern
		switch (this.type) {
		case 'preface':
			if(item.type == 'category') {
				this.items[key] = new Category(item, params, this);
				if(noPHPMode) btn_coords.push(""+item.start_x+""+item.start_y);
			} else if(item.type == 'button'){
				this.items[key] = new Button(item, params, this);
				if(noPHPMode) btn_coords.push(""+item.x+""+item.y);
			}
			break;
		case 'category':
			if(i == 0 && params.ctg_id == null && autoSelect) params.ctg_id = key;
			this.items[key] = new Category(item, params, this);
			break;
		case 'project':
			if(i == 0 && params.prj_id == null && autoSelect) params.prj_id = key;
			this.items[key] = new Project(item, params, this);
			break;
		case 'button':
			if(i == 0 && params.btn_id == null && autoSelect) params.btn_id = key;
			this.items[key] = new Button(item, params, this);
			if(noPHPMode) btn_coords.push(""+item.x+""+item.y);
			interactive = new Boolean(item.interactive);
			break;
		}
		i++;
	}
	if(this.type == 'button' || this.type == 'preface') {
		if(noPHPMode){
			var dummies = ["<div id='dummies'>"];
			var max_x = site.grid_w;
			if (this.type == 'preface')
				var max_y = site.grid_h+1;
			else
				var max_y = site.grid_h;
			for(var x=0; x < max_x; x++) {
				for(var y=0; y < max_y; y++) {
					var left = x*site.gridSize;
					var top = y*site.gridSize;
					if($.inArray(""+x+""+y, btn_coords) < 0) {
						dummies.push("<div id='dummy_"+x+""+y+"' class='dummy item' style='left: "+left+"px; top: "+top+"px;'></div>\n");
					}
				}
			}
			dummies.push("</div>");
			this.$scrollWrapper.append(dummies.join(''));
			$('.dummy').draggable({
				revert: true,
				revertDuration: site.navAnimationDuration
			});
		}
	}
	this.visibleAreaX = this.$div.width();
	this.visibleAreaY = this.$div.height();
	if (this.$div.hasClass('nav_horizontal')) {
		this.height = site.gridSize - 5;
		this.width = this.length()*site.gridSize - 5;
	} else if (this.$div.hasClass('nav_vertical')) {
		this.height = this.length()*site.gridSize - 5;
		this.width = site.gridSize - 5;
	} else {
		this.height = site.grid_h*site.gridSize - 5;
		this.width = site.grid_w*site.gridSize - 5;
	}
    /*Shadowbox.clearCache();
    Shadowbox.setup(".lightbox", {
    	gallery:            "Project Gallery",
        overlayColor: 		"#232323",
    	overlayOpacity: 	0.95,
    	continuous:			true
    });*/
};
/**
 * Lädt Item-Daten aus der Datenbank, instanziiert damit Item-Objekte
 * die im Item-Container-Objekt gespeichert und anschließend angezeigt werden.
 * 
 * @param params 		Parameter Objekt: {prefix, ctg_id und prj_id}
 * @param preSelection	ID des Items das nach dem laden ausgewählt werden soll.
 * @param autoselect	Automatische auswahl des ersten Items wenn true
 * @return
 */
ItemContainer.prototype.load = function(params, autoSelect) {
	if(params) {
		if(noPHPMode && fadeContent) {
			this.$div.hide();
		}
		if (this.type == 'project')
			this.$div.scrollTop(0);
		if(this.type == 'preface') {
			params.prefix = 'ctg';
			this.items = new Object();
			var handle = this;
			$.getJSON(this.urlLoad, params, function(response){
				//wenn anfrage erfolgreich und items nicht leer
				if(response.result && response.items != null) {
					var items_temp = response.items;
					params.prefix = 'btn';
					params.ctg_id = 0;
					$.getJSON(handle.urlLoad, params, function(response){
						//wenn anfrage erfolgreich und items nicht leer
						if(response.result && response.items != null) {
							var items_temp2 = response.items;
							for(key in items_temp2) {
								items_temp['btn'+key] = items_temp2[key];
							}
							handle.createItems(items_temp, params, autoSelect);
						} else {
							if(debug) alert('load ' + handle.type + ' failed:\n'
									+ 'error: ' +response.error +"\n"
									+ 'items: ' +response.items +"\n"
									+ 'itemContainer: ' +(handle.$div.length > 0));
						}
					});
				} else {
					if(debug) alert('load ' + handle.type + ' failed:\n'
							+ 'error: ' +response.error +"\n"
							+ 'items: ' +response.items +"\n"
							+ 'itemContainer: ' +(handle.$div.length > 0));
				}
			});
		} else {
			params.prefix = this.prefix;
			this.items = new Object();
			var handle = this;
			$.getJSON(this.urlLoad, params, function(response){
				//wenn anfrage erfolgreich und items nicht leer
				if(response.result && response.items != null) {
					handle.createItems(response.items, params, autoSelect);
				} else {
					if(debug) alert('load ' + handle.type + ' failed:\n'
							+ 'error: ' +response.error +"\n"
							+ 'items: ' +response.items +"\n"
							+ 'itemContainer: ' +(handle.$div.length > 0));
				}
			});
		}
	} else {
		if(debug) alert("Fehlende Parameter für load"+this.type+"()!");
	}
	if(noPHPMode) {
		this.$div.fadeIn(site.containerFadeDuration);
		this.$scrollWrapper.stop().animate({top: 0, left: 0}, 1000, 'easeOutQuad');
		
	   
		$(".lightbox").fancybox({
			openEffect: 'fade',
			closeEffect: 'fade',
			nextEffect: 'fade',
			prevEffect: 'fade',
			padding: 1,
			closeBtn: false,
			helpers	: {
				title	: {
					type: 'inside'
				},
				overlay	: {
					opacity : 0.95,
					css : {
						'background-color' : '#232323'
					}
				},
				thumbs	: {
					width	: 70,
					height	: 70
				}
			}
			
		});
	}
};

/**
 * Scrollt MenuContainer wenn er mehr Menü Items enthält als darstellbar sind
 * 
 * @param e eventHandler des mousmove listeners
 * @return void
 */
var lastMouseY = 0;
var lastMouseX = 0;
ItemContainer.prototype.scroll = function(e) {
	if (Math.abs(e.pageY - lastMouseY) > 30 || Math.abs(e.pageX - lastMouseX) > 50) {
		this.$scrollWrapper.stop().animate({top: this.scrollVertical(e), left: this.scrollHorizontal(e)}, 1000, 'easeOutQuad');
		lastMouseY = e.pageY;
		lastMouseX = e.pageX;
	}
};
ItemContainer.prototype.scrollVertical = function(e) {
	var mouse = e.pageY - this.$div.offset().top - this.scrollThreshold;
	if (mouse < 0) mouse = 0;
	var mouseQuantized = mouse / (this.visibleAreaY - this.scrollThreshold*2);
	if (mouseQuantized > 1) mouseQuantized = 1;
	var menuSurplus = this.height - this.visibleAreaY;
	return -(mouseQuantized * menuSurplus);
};
ItemContainer.prototype.scrollHorizontal = function(e) {
	var mouse = e.pageY - this.$div.offset().left - this.scrollThreshold;
	if (mouse < 0) mouse = 0;
	var mouseQuantized = mouse / (this.visibleAreaX - this.scrollThreshold*2);
	if (mouseQuantized > 1) mouseQuantized = 1;
	var menuSurplus = this.width - this.visibleAreaX;
	return -(mouseQuantized * menuSurplus);
};